package kulstats.server;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kulstats.Course;
import kulstats.CourseManager;
import kulstats.Milestone;
import kulstats.MilestoneController;
import kulstats.MilestoneManager;
import kulstats.Registry;
import kulstats.User;
import kulstats.UserManager;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;


public class MilestoneServlet extends  HttpServlet{
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws IOException {
    	//do nothing
    	resp.sendRedirect("/milestones");
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		    throws IOException {
		UserManager userManager = Registry.userManager();
	    User currentUser = userManager.getCurrentUser();
	    if(currentUser == null) {
	    	resp.sendRedirect("/login");
	    	return;
	    }
	    JSONObject answer = new JSONObject();
	    String doAction = req.getParameter("milestone_action");
	 	System.out.println("Action: " + doAction);
	 	

		MilestoneController milestoneController = MilestoneController.getInstance();
		MilestoneManager milestoneManager = Registry.milestoneManager();
		CourseManager courseManager = Registry.courseManager();
	 	
		if(doAction.equals("milestone_new"))
		{
		 	//calculate the date of last Monday 00:00
			Calendar now = Calendar.getInstance();  
			int weekday = now.get(Calendar.DAY_OF_WEEK);  
			if (weekday != Calendar.MONDAY)  
			{  
				// calculate how much to add  
			 	// the 2 is the difference between Saturday and Monday  
			 	int days = (Calendar.SATURDAY - weekday + 2) % 7;  
			 	now.add(Calendar.DAY_OF_YEAR, days);  
			}  
			int year =now.get(Calendar.YEAR);
			int month= now.get(Calendar.MONTH);
			int day = now.get(Calendar.DAY_OF_MONTH);
			day = day-7;
			now.set(year,month,day,0,0,0);
			// now convert to Date  
			Date lastMonday = now.getTime();
			now.add(Calendar.DAY_OF_MONTH, 7);
			Date nextMonday = now.getTime();
			
		 	String courseID = req.getParameter("mst_course");
		 	Course course = courseManager.getCourseByID(courseID);
		 	int hours = (int)Integer.parseInt(req.getParameter("hours"));
		 	boolean reached = false;
		 	boolean predefined = true;
		 	System.out.println(courseID +";"+hours);
		 	if(hours <= 0) {System.out.println("hours = null");}
		 	
		 	Milestone mst = new Milestone(lastMonday,nextMonday,predefined,course,hours,reached);
		 	if(mst != null) {
		 		
		 		if(milestoneController.saveMilestone(mst)) {
		 			answer.put("status","success");
		 		}
		 		else {
			 		answer.put("status","fail");
			 	}
		 	}
		 	
		 	
		}
		else if(doAction.equals("milestones_get")) {

			Map<String, LinkedList<Double>> unfinished = milestoneManager.getUnfinishedMilestones(currentUser);
		 	System.out.println(unfinished);
			if(unfinished.isEmpty()) {
				answer.put("status","empty");
			}
			else{
				Iterator it = unfinished.keySet().iterator();
				answer.put("status","success");
				//List<JSONObject> mls = new List<JSONObject>();
				JSONArray mls = new JSONArray();
				while (it.hasNext()){
					String key = (String)it.next();
					double progress = (double)unfinished.get(key).get(0);
					double progressPerc = progress*100;
					JSONObject ml = new JSONObject();
					ml.put("course",key);
					ml.put("progress",progressPerc);
					ml.put("hours",unfinished.get(key).get(1));
					mls.add(ml);
				}
				answer.put("milestones",mls);
			}
		}

	 	 
	 	resp.setContentType("text/plain");
    	resp.getWriter().println(answer);
	 
	}
}
